package util;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * ClassName:CGLIBProxy
 * Package:util
 *
 * @date:2021/11/2 2:12 下午
 * @author: Tiangle
 *
 * CGlib动态代理
 */
public class CGLIBProxy implements MethodInterceptor {

    public <T>T getProxy(Class<T> clazz){
        Enhancer enhancer = new Enhancer();
        //设置父类类型
        enhancer.setSuperclass(clazz);
        //拦截后的回调处理
        enhancer.setCallback(this);
        //创对象
        return (T) enhancer.create();
    }





    /*
      o - 真实对象
      objects - 参数列表
      methodProxy - 真实对象方法的代理对象
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object rv = null;

        try {
            System.out.println("start");
            rv = methodProxy.invokeSuper(o, objects);
            System.out.println("ok");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("rollback");
        }


        return rv;
    }
}
